import router from './router'
import store from './store'
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css'// Progress 进度条样式
import { Message } from 'element-ui'
import { getToken, getRefreshToken, setToken, setRefreshToken } from '@/utils/auth' // 验权
import request from '@/utils/request'

const whiteList = ['/sys/login'] // 不重定向白名单
router.beforeEach((to, from, next) => {
  NProgress.start()
  if (getToken()) {
    if (to.path === '/sys/login') {
      next({ path: '/' })
      NProgress.done() // if current page is dashboard will not trigger	afterEach hook, so manually handle it
    } else {
      if (!store.getters.name) {
        store.dispatch('GetInfo').then(res => { // 拉取用户信息
          next()
        }).catch((err) => {
          store.dispatch('FedLogOut').then(() => {
            Message.error(err || 'Verification failed, please login again')
            next({ path: '/' })
          })
        })
      } else {
        next()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      if (getRefreshToken()) { // 如果refresh_token还在
        request({
          url: '/system/refresh',
          method: 'post',
          params: {
            refresh_token: getRefreshToken()
          }
        }).then(response => {
          if (response.code === 1) {
            setToken(response.data.DefaultOAuth2AccessToken.access_token)
            setRefreshToken(response.data.DefaultOAuth2AccessToken.refresh_token)
            store.dispatch('SetToken', response.data.DefaultOAuth2AccessToken.access_token)
            if (getToken()) {
              next()
            } else {
              next('/sys/login')
              NProgress.done()
            }
          } else {
            next('/sys/login')
            NProgress.done()
          }
        }).catch(error => {
          console.log(error)
          next('/sys/login')
          NProgress.done()
        })
      } else {
        // location.reload()
        next('/sys/login')
        NProgress.done()
      }
    }
  }
})

router.afterEach(() => {
  NProgress.done() // 结束Progress
})
